package tool

import (
	"fmt"
	"lsgfish/server/internal/config"
	"lsgfish/server/internal/model"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

func InitDB() error {
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		config.Conf.DB.Username,
		config.Conf.DB.Password,
		config.Conf.DB.Protocol,
		config.Conf.DB.Port,
		config.Conf.DB.Database,
	)

	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:                                   logger.Default.LogMode(logger.Info),
		DisableForeignKeyConstraintWhenMigrating: true,
		SkipDefaultTransaction:                   true,
	})

	if err != nil {
		return fmt.Errorf("连接数据库失败: %w", err)
	}

	// 自动迁移
	if config.Conf.DB.AutoMigrate {
		if err := AutoMigrate(); err != nil {
			return fmt.Errorf("数据库迁移失败: %w", err)
		}
	}

	return nil
}

// 数据库自动迁移
func AutoMigrate() error {
	return DB.AutoMigrate(
		&model.User{},
		&model.UserRole{},
		&model.Menu{},
		&model.MenuMeta{},
		&model.Role{},
		&model.RoleMenu{},
		&model.DictType{},
		&model.DictData{},
	)
}
